package com.mobilepay.moneypig.model.activity.mine;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.TipDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.CreditListData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.acache.ACache;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/7/29 0029
 */

public class CreditCardActivity extends BaseActivity {
    private static final String TAG = "CreditCardActivity";
    private RecyclerView mCardRecycle;
    private CreditCardAdapter mCardAdapter;
    private RelativeLayout mRelativeBack;
    private RelativeLayout mTextAdd;
    private List<CreditListData.DataBean> dataBeanList;
    private SmartRefreshLayout refreshLayout;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_credit_card);
    }

    @Override
    protected void initViews() {
        mCardRecycle = (RecyclerView) findViewById(R.id.credit_card_recycle);
        mRelativeBack = (RelativeLayout) findViewById(R.id.card_back);
        mTextAdd = (RelativeLayout) findViewById(R.id.card_add);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.credit_refresh);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setAdapter();
        getData();
    }

    private void getData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.creditCard);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("sign", param.getMd5String());
        showProgress("加载中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                refreshLayout.finishRefresh();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString(NetConfig.creditCard);
                    if (!CommonUtil.isEmpty(jsonString)) {
                        setCreditData(jsonString);
                    }
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                refreshLayout.finishRefresh();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 0) {
                        showToastShort(responseResult.getInfo());
                    } else {
                        ACache.get(App.getApp()).put(NetConfig.creditCard, string);
                        setCreditData(string);
                    }
                }
            }
        });
    }

    private void setCreditData(String string) {
        CreditListData data = GsonUtil.GsonToBean(string, CreditListData.class);
        if (dataBeanList.size() != 0) {
            dataBeanList.clear();
        }
        if (data.getData().size() != 0) {
            dataBeanList.addAll(data.getData());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCardAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    private void setAdapter() {
        dataBeanList = new ArrayList<>();
        mCardAdapter = new CreditCardAdapter(this);
        mCardAdapter.setData(dataBeanList);
        mCardRecycle.setLayoutManager(new LinearLayoutManager(this));
        mCardRecycle.setAdapter(mCardAdapter);
    }

    @Override
    protected void onSetListener() {
        mRelativeBack.setOnClickListener(this);
        mTextAdd.setOnClickListener(this);
        mCardAdapter.setOnDeleteListener(new CreditCardAdapter.OnCreditDeleteListener() {
            @Override
            public void deleteCredit(String id) {
                if (id != null) {
                    showTipDialog(id);
                }
            }
        });

        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData();
            }
        });
    }

    private TipDialog tipDialog;

    private void showTipDialog(final String id) {
        if (tipDialog == null) {
            tipDialog = new TipDialog(this);
        }
        tipDialog.setCancelable(true);
        tipDialog.setContent("确定删除信用卡？");
        tipDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                tipDialog.dismiss();
                deleteCredit(id);
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                tipDialog.dismiss();
            }
        });
        tipDialog.show();

    }

    private void deleteCredit(String id) {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.deleteCredit);
        param.add("uid", String.valueOf(App.getApp().getUserDetailInfo().getData().getUid()));
        param.add("id", id);
        param.add("sign", param.getMd5String());
        showProgress("处理中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToastShort(responseResult.getInfo());
                    if (responseResult.getStatus() == 1) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                getData();
                            }
                        });
                    }
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.card_back:
                finish();
                break;
            case R.id.card_add:
                startActivity(AddCreditActivity.class, false, false);
                break;
        }
    }

    private static class CreditCardAdapter extends RecyclerView.Adapter<CreditCardAdapter.CardHolder> {

        private Context mContext;
        private LayoutInflater mInflater;
        private List<CreditListData.DataBean> list;

        CreditCardAdapter(Context mContext) {
            this.mContext = mContext;
            mInflater = LayoutInflater.from(mContext);
        }

        private void setData(List<CreditListData.DataBean> beanList) {
            this.list = beanList;
        }

        @Override
        public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mInflater.inflate(R.layout.item_credit_card, parent, false);
            return new CardHolder(view);
        }

        @Override
        public void onBindViewHolder(CardHolder holder, int position) {
            final CreditListData.DataBean data = list.get(position);
            if (data != null) {
                holder.mTextBankName.setText(data.getBank_name());
                String bankNum = data.getCard_code();
                String newString = "";
                newString = CommonUtil.StringOpt(bankNum, 3, bankNum.length() - 4);
//                if (bankNum.length() > 16) {
//                    newString = CommonUtil.StringOpt(bankNum, 3, 16);
//                } else {
//                    newString = CommonUtil.StringOpt(bankNum, 3, 12);
//                }
                holder.mTextCardNum.setText(newString);
                Glide.with(holder.itemView.getContext())
                        .load(CommonUtil.getPathFromAssets(data.getBank_name(), mContext))
                        .into(holder.mImageAvatar);
                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        listener.deleteCredit(String.valueOf(data.getId()));
                        return true;
                    }
                });
                holder.mLinearDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listener.deleteCredit(String.valueOf(data.getId()));
                    }
                });
            }
//
//            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View v) {
//                    listener.deleteCredit(String.valueOf(""));
//                    return true;
//                }
//            });
//            holder.mLinearDelete.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    listener.deleteCredit(String.valueOf(""));
//                }
//            });
        }

        public void setOnDeleteListener(OnCreditDeleteListener listener) {
            this.listener = listener;
        }

        private OnCreditDeleteListener listener;

        interface OnCreditDeleteListener {
            void deleteCredit(String id);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class CardHolder extends RecyclerView.ViewHolder {
            private ImageView mImageAvatar;
            private TextView mTextBankName;
            private TextView mTextCardType;
            private TextView mTextCardNum;
            private LinearLayout mLinearDelete;

            CardHolder(View itemView) {
                super(itemView);
                mImageAvatar = (ImageView) itemView.findViewById(R.id.bank_card_image);
                mTextBankName = (TextView) itemView.findViewById(R.id.bank_name);
                mTextCardType = (TextView) itemView.findViewById(R.id.card_type);
                mTextCardNum = (TextView) itemView.findViewById(R.id.card_num);
                mLinearDelete = (LinearLayout) itemView.findViewById(R.id.credit_delete);
            }
        }
    }
}
